/**
 * OSAmI: Open Source Ambient Intelligence
 * Copyright (C) 2010 Bull S.A.S.
 * Contact: osami-general@osami-commons.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 */

package org.osami.gateway.jennic.internal;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.List;

import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Instantiate;
import org.apache.felix.ipojo.annotations.Provides;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.ServiceProperty;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.device.Constants;
import org.osgi.service.device.Device;
import org.osgi.service.device.Driver;

/**
 * Created by IntelliJ IDEA.
 * User: guillaume
 * Date: 16 juin 2010
 * Time: 13:39:59
 * To change this template use File | Settings | File Templates.
 */
@Component
@Provides
@Instantiate
public class JennicDriver implements Driver {

    @ServiceProperty(name = Constants.DRIVER_ID,
                     value = "org.osami.driver.jennic-1.0")
    private String driverId;

    @Requires(filter = "(factory.name=org.osami.gateway.jennic.internal.temperature.TemperatureSense)")
    private Factory temperatureSenseFactory;

    @Requires(filter = "(factory.name=org.osami.gateway.jennic.internal.humidity.HumiditySense)")
    private Factory humiditySenseFactory;

    @Requires(filter = "(factory.name=org.osami.gateway.jennic.internal.light.LightSense)")
    private Factory lightSenseFactory;

    private List<String> attachedSerials;
    private BundleContext bundleContext;

    public JennicDriver(BundleContext bundleContext) {
        this.bundleContext = bundleContext;
        this.attachedSerials = new ArrayList<String>();
    }

    public int match(ServiceReference reference) throws Exception {
        String[] categories = (String[]) reference.getProperty(Constants.DEVICE_CATEGORY);
        if (categories != null) {
            if (Arrays.asList(categories).contains("Jennic")) {

                // This device belongs to us :)

                // First try an exact match with serial ...
                String serial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
                if (serial != null) {
                    if (attachedSerials.contains(serial)) {
                        return JennicDevice.MATCH_SERIAL;
                    }
                }

                // Then try the
                String type = (String) reference.getProperty("device.type");
                if (type != null) {
                    if ("jennic".equals(type)) {
                        return JennicDevice.MATCH_TYPE;
                    }
                }

            }
        }
        return Device.MATCH_NONE;
    }

    public String attach(final ServiceReference reference) throws Exception {

        // Attach the device
        String serial = (String) reference.getProperty(Constants.DEVICE_SERIAL);
        String topic = (String) reference.getProperty("topic");

        if (!attachedSerials.contains(serial)) {
            attachedSerials.add(serial);

            // Create the JennicSensors ...
            Dictionary<String, Object> deviceIdFilter = new Hashtable<String, Object>();
            deviceIdFilter.put("device", "(" + Constants.DEVICE_SERIAL + "=" + serial + ")");

            Dictionary<String, Object> temperatureConfiguration = new Hashtable<String, Object>();
            temperatureConfiguration.put("device.id", serial);
            temperatureConfiguration.put("topic", topic);
            temperatureConfiguration.put("name", "temperature");
            temperatureConfiguration.put("requires.filters", deviceIdFilter);
            temperatureSenseFactory.createComponentInstance(temperatureConfiguration);

            Dictionary<String, Object> humidityConfiguration = new Hashtable<String, Object>();
            humidityConfiguration.put("device.id", serial);
            humidityConfiguration.put("topic", topic);
            humidityConfiguration.put("name", "humidity");
            humidityConfiguration.put("requires.filters", deviceIdFilter);
            humiditySenseFactory.createComponentInstance(humidityConfiguration);

            Dictionary<String, Object> lightConfiguration = new Hashtable<String, Object>();
            lightConfiguration.put("device.id", serial);
            lightConfiguration.put("topic", topic);
            lightConfiguration.put("name", "light");
            lightConfiguration.put("requires.filters", deviceIdFilter);
            lightSenseFactory.createComponentInstance(lightConfiguration);
        }

        // It is expected to return null if we have directly attached the device to our driver.
        return null;
    }
}
